package me.shiqiang.im.linsteners;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnEvent;
import me.shiqiang.im.enums.MessageCmd;
import me.shiqiang.im.enums.MessageMType;
import me.shiqiang.im.msg.MsgBody;
import me.shiqiang.im.msg.NewMsg;
import me.shiqiang.im.server.ConnectionContext;
import me.shiqiang.im.service.ChatSwitchService;
import me.shiqiang.im.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;

/**
 * @author cuishiqiang
 * @date 2018/1/15 上午10:22
 */
@Component("NewMsgListener")
public class NewMsgListener extends Listener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${newMsg.producer.topic}")
    private String topic;

    @Autowired
    Producer producer;

    @Autowired
    ChatSwitchService chatSwitchService;

    @OnEvent(MessageCmd.NEW_MSG)
    public void resp(SocketIOClient client, NewMsg resp) {
        Long userId = resp.getUserId();
        if (!chatSwitchService.chatSwitch(userId)) {
            return;
        }
        String clientId = ConnectionContext.getInstance().get(userId.toString());
        try {
//            logger.info("Resp.msgBody"+resp.getMsgBody()+"+++Resp"+resp.toString());
            MsgBody msgBody = resp.getMsgBody();
            if (clientId == null) {
                if (MessageMType.NOTICE.equalsIgnoreCase(String.valueOf(msgBody.getmType()))) {
                    return;
                }
                logger.info("clientId为null,{}已发送通知消息", JsonUtils.getInstance().toJson(resp));
                sendMqMsg(String.valueOf(msgBody.getcType()), JsonUtils.getInstance().toJson(resp));
//                logger.info(JsonUtils.getInstance().toJson(resp));
                return;
            }
            SocketIOClient userClient = server.getClient(UUID.fromString(clientId));
            if (userClient == null) {
                if (MessageMType.NOTICE.equalsIgnoreCase(String.valueOf(msgBody.getmType()))) {
                    return;
                }
                logger.info("userClient为null,已发送通知消息");
                sendMqMsg(String.valueOf(msgBody.getcType()), JsonUtils.getInstance().toJson(resp));
                logger.info(JsonUtils.getInstance().toJson(resp));
                return;
            }

//            logger.info(String.format("clientId为%s,userClient:%s",clientId,userClient));
            userClient.sendEvent(MessageCmd.NEW_MSG, resp);
        } catch (IOException e) {
            logger.error("发生异常", e);
        }

    }


    private void sendMqMsg(String cType, String body) {
        Message msg = new Message();
        msg.setTopic(topic);
        msg.setTag(cType);
        msg.setBody(body.getBytes());
        producer.sendOneway(msg);
    }
}
